package webapi.storage.localdisk;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import webapi.storage.ReadOnlyDataChunk;
import webapi.storage.StorageService;
import webapi.storage.WriteOnlyDataChunk;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@Service
public class LocalDiskStorageService implements StorageService {
    private final Logger logger = LoggerFactory.getLogger(LocalDiskStorageService.class);
    private final LocalDiskStorageProperties properties;
    private final Path storageRootPath;

    public LocalDiskStorageService(LocalDiskStorageProperties localDiskStorageProperties) {
        properties = localDiskStorageProperties;
        storageRootPath = Paths.get(properties.getLocation());
        if (Files.notExists(storageRootPath)) {
            logger.info("创建文件夹: {}", storageRootPath.toString());
            try {
                Path createdDir = Files.createDirectories(storageRootPath);
            } catch (IOException err) {
                logger.error("创建文件夹失败: {}: {}", storageRootPath.toString(), err.getMessage());
                throw new RuntimeException("创建文件夹失败: " + storageRootPath.toString(), err);
            }
        } else if (Files.isRegularFile(storageRootPath)) {
            logger.error("创建文件夹失败: {} 已经被其他文件占用, 请手动删除该文件", storageRootPath.toString());
            throw new RuntimeException("文件夹配置无效: " + storageRootPath.toString() + "是一个普通文件而非文件夹, 请手动删除该文件");
        }
        if (!Files.isReadable(storageRootPath)) {
            logger.info("无法访问文件夹: {}", storageRootPath.toString());
            throw new RuntimeException("无法访问文件夹: " + storageRootPath.toString());
        }
    }

    @Override
    public boolean serviceIsOnline() {
        return Files.isReadable(storageRootPath);
    }

    @Override
    public WriteOnlyDataChunk createChunkAndOpenWriteOnly(String chunkName) throws IOException {
        Path filePath = storageRootPath.resolve(chunkName);
        return new LocalDiskWriteOnlyDataChunk(filePath);
    }

    @Override
    public ReadOnlyDataChunk openChunkReadOnly(String chunkName) throws IOException {
        Path filePath = storageRootPath.resolve(chunkName);
        return new LocalDiskReadOnlyDataChunk(filePath);
    }
}
